package com.jcj.jcjregistry.health;

import com.jcj.jcjregistry.model.InstanceMeta;
import com.jcj.jcjregistry.service.JcjRegistryService;
import com.jcj.jcjregistry.service.RegistryService;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

@Slf4j
public class JcjHealthChecker implements HealthChecker {

    RegistryService registryService;
    final ScheduledExecutorService executorService = Executors.newScheduledThreadPool(1);
    long timeout = 20_000;

    public JcjHealthChecker(RegistryService registryService) {
        this.registryService = registryService;
    }


    @Override
    public void start() {
        executorService.scheduleWithFixedDelay(() -> {
            log.info("health checker start");
            long now = System.currentTimeMillis();

            JcjRegistryService.TIMESTAMPS.keySet().stream().forEach(serviceAndInstance -> {
                long timestamp = JcjRegistryService.TIMESTAMPS.get(serviceAndInstance);
                if (now - timestamp > timeout) {
                    log.info("health checker timeout,unregister {}", serviceAndInstance);
                    String[] split = serviceAndInstance.split("@");
                    String serviceName = split[0];
                    String instanceUrl = split[1];
                    InstanceMeta instance = InstanceMeta.from(instanceUrl);
                    registryService.unregister(serviceName, instance);
                    JcjRegistryService.TIMESTAMPS.remove(serviceAndInstance);
                }
            });
        }, 10, 10, TimeUnit.SECONDS);
    }

    @Override
    public void stop() {
        executorService.shutdown();
    }
}
